'use strict';

const conn = require('../../libs/Conn');

module.exports = async function (params) {
    /*排序*/
    let orderBySql = ``;
    if(params.sort&&params.dir){
        switch (params.sort) {
            case 'unit_name':
                orderBySql = `ORDER BY unit_name ${params.dir}`;
                break;
            case 'type_name':
                orderBySql = `ORDER BY unit_type ${params.dir}`;
                break;
            case 'enable':
                orderBySql = `ORDER BY enable ${params.dir}`;
                break;
        }
    }
    /*分页*/
    let pageSql = `LIMIT ${params.pageNum>1?((params.pageNum-1)*10):0},10;SELECT FOUND_ROWS() AS count`;

    let querySql = `SELECT
                        SQL_CALC_FOUND_ROWS
                        unit_id,
                        unit_type,
                        unit_name,
                        enable
                    FROM
                        unit_file 
                    WHERE
                        delete_sign = 1 ${orderBySql} ${pageSql}`;

    let rec = await conn(querySql);
    let pageNum = Math.ceil(rec[1][0].count/10);
    for(let data in rec[0]){
        switch (rec[0][data].enable) {
            case 1:
                rec[0][data].enable_char = '启用';
                break;
            case 2:
                rec[0][data].enable_char = '禁用';
                break;
        }

        switch (rec[0][data].unit_type) {
            case 1:
                rec[0][data].type_name = '建设单位';
                break;
            case 2:
                rec[0][data].type_name = '设计单位';
                break;
            case 3:
                rec[0][data].type_name = '施工单位';
                break;
            case 4:
                rec[0][data].type_name = '监理单位';
                break;
            case 5:
                rec[0][data].type_name = '勘察单位';
                break;
            case 6:
                rec[0][data].type_name = '图审单位';
                break;
        }
    }
    if(rec[0].length>0){
        rec[0][0].dataTotal = rec[1][0].count;
        rec[0][0].pageTotal = pageNum;
        rec[0][0].pageNum = params.pageNum;
    }
    return {success: true, data: rec[0]};

};